package com.lmb.service.impl;

import com.lmb.bean.ResidentEmergencies;
import com.lmb.bean.UserLogin;
import com.lmb.mapper.ResidentEmergenciesDao;
import com.lmb.mapper.UserLoginDao;
import com.lmb.util.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@Component
public class OSSImageCleanOnStartup implements CommandLineRunner {

    @Autowired
    private UserLoginDao userLoginDao;

    @Autowired
    private ResidentEmergenciesDao residentEmergenciesDao;

    @Override
    public void run(String... args) throws Exception {
        System.out.println("项目启动，开始执行OSS图片清理任务...");
        cleanUnusedImages();
        System.out.println("OSS图片清理任务执行完毕");
    }

    private void cleanUnusedImages() {
        try {
            // 1. 获取所有被引用的图片名称集合
            Set<String> usedImageNames = new HashSet<>();

            // 2. 处理user_login表的photo字段（兼容空值）
            List<UserLogin> userLogins = userLoginDao.findAll();
            if (userLogins != null && !userLogins.isEmpty()) {
                for (UserLogin user : userLogins) {
                    if (user != null && user.getPhoto() != null && !user.getPhoto().trim().isEmpty()) {
                        String fileName = extractFileNameFromUrl(user.getPhoto().trim());
                        if (fileName != null) {
                            usedImageNames.add(fileName);
                        }
                    }
                }
            }

            // 3. 处理resident_emergencies表的images字段（兼容空值）
            List<ResidentEmergencies> emergencies = residentEmergenciesDao.findAll();
            if (emergencies != null && !emergencies.isEmpty()) {
                for (ResidentEmergencies emergency : emergencies) {
                    if (emergency != null && emergency.getImages() != null && !emergency.getImages().trim().isEmpty()) {
                        String[] imageUrls = emergency.getImages().trim().split(",");
                        for (String url : imageUrls) {
                            if (url != null && !url.trim().isEmpty()) {
                                String fileName = extractFileNameFromUrl(url.trim());
                                if (fileName != null) {
                                    usedImageNames.add(fileName);
                                }
                            }
                        }
                    }
                }
            }

            // 4. 获取OSS上的所有图片
            List<String> ossImageNames = ImageUtil.getFilelist();
            if (ossImageNames == null) {
                ossImageNames = new ArrayList<>();
            }

            // 5. 筛选未被引用的图片
            List<String> unusedImages = ossImageNames.stream()
                    .filter(ossName -> ossName != null && !usedImageNames.contains(ossName))
                    .collect(Collectors.toList());

            // 6. 批量删除
            if (!unusedImages.isEmpty()) {
                ImageUtil.deleteList(unusedImages);
                System.out.println("清理完成，共删除 " + unusedImages.size() + " 张图片：" + unusedImages);
            } else {
                System.out.println("没有需要清理的未使用图片");
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("启动时OSS清理任务执行失败：" + e.getMessage());
        }
    }

    // 从URL中提取文件名
    private String extractFileNameFromUrl(String url) {
        if (url == null || url.trim().isEmpty()) {
            return null;
        }
        try {
            String baseUrl = "https://" + ImageUtil.BUCKET_NAME + "." + ImageUtil.ENDPOINT + "/";
            if (url.startsWith(baseUrl)) {
                return url.substring(baseUrl.length());
            }
            int lastSlashIndex = url.lastIndexOf("/");
            if (lastSlashIndex != -1 && lastSlashIndex < url.length() - 1) {
                return url.substring(lastSlashIndex + 1);
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}